import { login, logout, getUserInfo, refreshToken } from '@/api/user';
import { getToken, setToken, removeToken, setUser, getUser, removeUser, getUserFromToken } from '@/utils/auth';
import { ROUTE_LOGIN } from '@/utils/constants';
import router from '@/router';

const state = {
  token: getToken(),
  userInfo: getUser(),
  roles: [],
  permissions: []
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions;
  }
};

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password, rememberMe } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password, rememberMe })
        .then(response => {
          const { token } = response;
          commit('SET_TOKEN', token);
          setToken(token);
          
          // 从token解析用户信息
          const userInfo = getUserFromToken(token);
          if (userInfo) {
            commit('SET_USER_INFO', userInfo);
            setUser(userInfo);
          }
          
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  
  // 获取用户信息
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then(response => {
          const { data } = response;
          
          if (!data) {
            reject('获取用户信息失败，请重新登录');
          }
          
          const { roles, permissions } = data;
          
          // 验证返回的roles是否是一个非空数组
          if (!roles || roles.length <= 0) {
            reject('用户角色不能为空');
          }
          
          commit('SET_ROLES', roles);
          commit('SET_PERMISSIONS', permissions);
          commit('SET_USER_INFO', data);
          setUser(data);
          
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  
  // 刷新Token
  refreshToken({ commit }) {
    return new Promise((resolve, reject) => {
      refreshToken()
        .then(response => {
          const { token } = response;
          commit('SET_TOKEN', token);
          setToken(token);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  
  // 用户登出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          commit('SET_PERMISSIONS', []);
          commit('SET_USER_INFO', null);
          removeToken();
          removeUser();
          
          // 重置路由
          router.push(ROUTE_LOGIN);
          
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  
  // 前端登出
  fedLogout({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      commit('SET_PERMISSIONS', []);
      commit('SET_USER_INFO', null);
      removeToken();
      removeUser();
      
      router.push(ROUTE_LOGIN);
      resolve();
    });
  },
  
  // 重置Token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      removeToken();
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}; 